package com.guang.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guang.controller.response.RespBean;
import com.guang.domain.UserInfo;
import com.guang.mapper.UserInfoMapper;
import com.guang.service.impl.EasyExcelServiceImpl;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/employee/excel")
@AllArgsConstructor
@Slf4j
public class EasyExcellController {


    @Autowired
    EasyExcelServiceImpl easyExcel;

    @Autowired
    private UserInfoMapper userMapper;

    /**
     * 导入百万excel文件
     * @param file
     * @return
     */
    @RequestMapping("/import")
    public RespBean easyExcelImport(MultipartFile file){
        if(file.isEmpty()){
            return RespBean.error("文件不可为空");
        }
        easyExcel.easyExcelImport(file);
        return RespBean.ok("文件导入成功");
    }



    /**
     * 下载用户信息模板
     * @param response
     */
    @RequestMapping("/exporttemplate")
    public void downloadTemplate(HttpServletResponse response){
        try {
            //设置文件名
            InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("template/用户信息模板.xlsx");
            //设置头文件,注意文件名若为中文，使用encode进行处理
            response.setHeader("Content-disposition", "attachment;fileName=" +  java.net.URLEncoder.encode("用户信息模板.xlsx", "UTF-8"));
            //设置文件传输类型与编码
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            OutputStream outputStream = response.getOutputStream();
            byte[] bytes = new byte[2048];
            int len;
            while((len = inputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,len);
            }
            outputStream.flush();
            outputStream.close();
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出百万excel文件
     * @param response
     */
    @RequestMapping("/easyexcelexport")
    public void easyExcelExport(HttpServletResponse response){
        try {
            //设置内容类型
            response.setContentType("text/csv");
            //设置响应编码
            response.setCharacterEncoding("utf-8");
            //设置文件名的编码格式,防止文件名乱码
            String fileName = URLEncoder.encode("用户信息", "UTF-8");
            //固定写法,设置响应头
            response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
            Integer total = userMapper.countNum();
            if (total == 0) {
                log.info("查询无数据");
                return;
            }
            //指定用哪个class进行写出
            ExcelWriter build = EasyExcel.write(response.getOutputStream(), UserInfo.class).build();
            //设置一个sheet页存储所有导出数据
            WriteSheet writeSheet = EasyExcel.writerSheet("sheet").build();
            long pageSize = 10000;
            long pages = total / pageSize;
            long startTime = System.currentTimeMillis();
            //数据量只有一页时直接写出
            if(pages < 1){
                List<UserInfo> users = userMapper.selectList(null);
                build.write(users, writeSheet);
            }
            //大数据量时，进行分页查询写入
            for (int i = 0; i <= pages; i++) {
                Page<UserInfo> page = new Page<>();
                page.setCurrent(i + 1);
                page.setSize(pageSize);
                Page<UserInfo> userPage = userMapper.selectPage(page, null);
                build.write(userPage.getRecords(), writeSheet);
            }
            build.finish();
            log.info("导出耗时/ms:"+(System.currentTimeMillis()-startTime)+",导出数据总条数："+total);
        } catch (Exception e) {
            log.error("easyExcel导出失败，e:{}",e.getMessage(),e);
        }
    }


}
